package com.example.gateway.config;

import com.example.gateway.handler.AuthenticationHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;

@Configuration
public class GatewayConfig {

    @Autowired
    private AuthenticationHandler authenticationHandler;

    @Bean
    public RouteLocator routeLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route(route -> route
                        .path("/api/login")
                        .filters(f -> f.stripPrefix(1)) // 去除请求前缀
                        .uri("http://localhost:8080")) // 直接转发到本地8080端口，可以根据实际情况来配置
                // 添加其他路由规则...
                .build();
    }

    // 网关自定义的路由处理，类似于 Servlet 中的 @RequestMapping 功能
    @Bean
    public RouterFunction<ServerResponse> routes() {
        return RouterFunctions
                .route(RequestPredicates.POST("/login"), authenticationHandler::handleLogin)
                .andRoute(RequestPredicates.POST("/register"), authenticationHandler::handleRegister);
    }

}

// Gateway 配置和使用参考 security-webflux 模块配置